package com.zrf.control;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.zrf.model.Product;
import com.zrf.pojo.Product;
import com.zrf.pojo.User;
import com.zrf.service.LogoService;
import com.zrf.service.ProductService;
import com.zrf.service.StorageService;
import com.zrf.service.UserService;

@RequestMapping("/pc")
@Controller
public class ProductControl {
	@Autowired
	private UserService us;
	@Autowired
	private ProductService ps;
	@Autowired
	private LogoService ls;
	@Autowired
	private StorageService ss;
	
	@RequestMapping(value="addp", params={"uname"})
	public String addp(Map<String, Object> mp,
					   @RequestParam("uname") String name,
					   Product p){
		if ((p==null)||p.getName().equals("商品名")
				||(p.getNum()==0)||(p.getPrice()==null)
				||(p.getPrice()==0.00d)) {
			return "redirect:/uc/yaddp?uname="+name;
		}
		
		User user = us.getUserByName(name);
		
		Integer sid = user.getStorage().getSid();
		
		Product pro = new Product(ss.findBySid(p.getSid()), p.getName(), p.getNum(), p.getPrice());
		
		ps.addOrUpdate(pro);
		
		return "redirect:/uc/first?name="+name+"&sid="+sid;
	}
	@RequestMapping(value="update", params={"uname","pid"})
	public String update(Map<String, Object> mp,
					   @RequestParam("uname") String name,
					   @RequestParam("pid") String pid){
		Integer sid = us.getUserByName(name).getStorage().getSid();
		mp.put("update", 0);
		mp.put("pid", pid);
		mp.put("uname", name);
		mp.put("storage", ps.getStorageById(sid));
		mp.put("storageAll", ps.findAll());
		mp.put("allp", ps.getAllProduct(sid));
		return "first";
	}
	
	@RequestMapping(value="truUpdate", params={"uname","pid","pnum","address","toSid"})
	public String truUpdate(Map<String, Object> mp,
					   @RequestParam("uname") String name,
					   @RequestParam("address") String address,
					   @RequestParam("toSid") int toSid,
					   @RequestParam("pid") int pid,
					   @RequestParam("pnum") int pnum){
		User user = us.getUserByName(name);
		
		Integer sid = user.getStorage().getSid();
		
		if (address.equals("1")&&(toSid!=sid)) {//转运到toSid仓库

			ls.addLogo(sid, toSid, pid, pnum, user);
		}else if ((!address.equals("1"))&&(toSid==sid)) {//发送到address地址

			ls.addToAddress(sid, address, pid, pnum, user);
		}
		return "redirect:/uc/first?name="+name+"&sid="+sid;
	}
	
	@RequestMapping(value="delete", params={"uname","pid"})
	public String truUpdate(Map<String, Object> mp,
					   @RequestParam("uname") String name,
					   @RequestParam("pid") int pid){
		User user = us.getUserByName(name);
		
		Integer sid = user.getStorage().getSid();
		
		ps.deleteByPid(pid);
		
		return "redirect:/uc/first?name="+name+"&sid="+sid;
	}
	
}